package com.guonl.open.api.client;


import com.guonl.open.api.response.OpenApiResult;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

public class RespDecoder implements Decoder {
    private final SpringDecoder springDecoder;

    public RespDecoder(SpringDecoder springDecoder) {
        this.springDecoder = springDecoder;
    }

    @Override
    @Bean
    public Object decode(Response response, Type type) throws IOException, FeignException {
        Object decode = springDecoder.decode(response, type);

        if (decode instanceof OpenApiResult) {
            OpenApiResult<?> _decode = (OpenApiResult<?>) decode;
            if (_decode.isSuccess()) {
                return _decode;
            }

            throw new FeignException.FeignClientException(
                response.status(),
                StringUtils.isBlank(_decode.getMessage()) ? String.valueOf(_decode.getCode()) : _decode.getMessage(),
                response.request(),
                (_decode.getCode() + "; " + _decode.getMessage()).getBytes(StandardCharsets.UTF_8),
                response.headers());
        }

        return decode;
    }
}
